<?php
if (!defined('SMF'))
	die('Hacking attempt...');

function calcplanetbeams($playerinfo,$ownerinfo,$sectorinfo,$planetinfo)
{
	global $smcFunc;
    global $basedefense, $dbtables;

    $energy_available = $planetinfo['energy'];
    $base_factor = ($planetinfo['base'] == 'Y') ? $basedefense : 0;
    $planetbeams = NUM_BEAMS($ownerinfo['beams'] + $base_factor);
	
	$result = $smcFunc['db_query']('', '
		SELECT *
		FROM {raw:db_ships}
		WHERE planet_id = {int:planet_id}
		AND on_planet = "Y"',
		array(
			'db_ships' => $dbtables['ships'],
			'planet_id' => $planetinfo['planet_id']
		)
	);
	
	while ($row = $smcFunc['db_fetch_assoc']($result))
    {
        $planetbeams = $planetbeams + NUM_BEAMS($row['beams']);
    }
	$smcFunc['db_free_result']($result);
	
    if ($planetbeams > $energy_available)
        $planetbeams = $energy_available;

    return $planetbeams;
}

function calcplanetfighters($planetinfo)
{
    $planetfighters = $planetinfo['fighters'];
    return $planetfighters;
}

function calcplanettorps($playerinfo,$ownerinfo,$sectorinfo,$planetinfo)
{
	global $smcFunc;
	global $level_factor, $basedefense, $dbtables;

    $base_factor = ($planetinfo['base'] == 'Y') ? $basedefense : 0;
	
	$result = $smcFunc['db_query']('', '
		SELECT *
		FROM {raw:db_ships}
		WHERE planet_id = {int:planet_id}
		AND on_planet = "Y"',
		array(
			'db_ships' => $dbtables['ships'],
			'planet_id' => $planetinfo['planet_id']
		)
	);
	
    $torp_launchers = round(mypw($level_factor, ($ownerinfo['torp_launchers']) + $base_factor)) * 10;
    $torps = $planetinfo['torps'];
	
	if ($smcFunc['db_num_rows']($result) > 0)
    {
		while ($row = $smcFunc['db_fetch_assoc']($result))
		{
			$ship_torps =  round(mypw($level_factor, $row['torp_launchers'])) * 10;
			$torp_launchers = $torp_launchers + $ship_torps;
		}
    }
	$smcFunc['db_free_result']($result);
	
    if ($torp_launchers > $torps)
        $planettorps = $torps;
    else
        $planettorps = $torp_launchers;
		
    $planetinfo['torps'] -= $planettorps;

    return $planettorps;
}

function calcplanetshields($playerinfo,$ownerinfo,$sectorinfo,$planetinfo)
{
	global $smcFunc;
	global $basedefense;
    global $dbtables;

    $base_factor = ($planetinfo['base'] == 'Y') ? $basedefense : 0;
	
	$result = $smcFunc['db_query']('', '
		SELECT *
		FROM {raw:db_ships}
		WHERE planet_id = {int:planet_id}
		AND on_planet = "Y"',
		array(
			'db_ships' => $dbtables['ships'],
			'planet_id' => $planetinfo['planet_id']
		)
	);
	
    $planetshields = NUM_SHIELDS($ownerinfo['shields'] + $base_factor);
    $energy_available = $planetinfo['energy'];
	
    while ($row = $smcFunc['db_fetch_assoc']($result))
    {
        $planetshields += NUM_SHIELDS($row['shields']);
    }

    if ($planetshields > $energy_available)
        $planetshields = $energy_available;

	$planetinfo['energy'] -= $planetshields;
	
    return $planetshields;
}

function planetbombing($playerinfo,$ownerinfo,$sectorinfo,$planetinfo)
{
	
	global $smcFunc, $txt, $scripturl;
    global $dbtables, $torp_dmg_rate;
	global $debug;
	
    if ($playerinfo['turns'] < 1)
    {
        echo $txt['bnt_cmb_atleastoneturn'], '<br><br>';
        TextMainMenu();
        die();
    }
	
	$lock = $smcFunc['db_query']('', '
		LOCK TABLES
		{raw:db_ships} WRITE,
		{raw:db_planets} WRITE',
		array(
			'db_ships' => $dbtables['ships'],
			'db_planets' => $dbtables['planets']
		)
	);

    echo $txt['bnt_bombsaway'], '<br><br>';

    $attackerfighterslost = 0;
    $planetfighterslost = 0;
	
    $attackerfightercapacity = NUM_FIGHTERS($playerinfo['computer']);
    $ownerfightercapacity = NUM_FIGHTERS($ownerinfo['computer']);
	
    $beamsused = 0;
	
    $planettorps = calcplanettorps($playerinfo,$ownerinfo,$sectorinfo,$planetinfo);
    $planetbeams = calcplanetbeams($playerinfo,$ownerinfo,$sectorinfo,$planetinfo);
    $planetfighters = calcplanetfighters($planetinfo);
	
    $attackerfighters = $playerinfo['ship_fighters'];
	
	if ($debug)
		echo 'FigsCapacity ', $attackerfightercapacity, ' <br>';
	if ($debug)
		echo 'Figsused ', $attackerfighters, '<br>';

    if ($ownerfightercapacity / $attackerfightercapacity < 1)
		echo $txt['bnt_bigfigs'], '<br><br>';

    if ($planetbeams <= $attackerfighters)
    {
        $attackerfighterslost = $planetbeams;
        $beamsused = $planetbeams;
    }
    else
    {
        $attackerfighterslost = $attackerfighters;
        $beamsused = $attackerfighters;
    }

    if ($attackerfighters <= $attackerfighterslost)
    {
        echo $txt['bnt_bigbeams'], '<br>';
        if ($debug)
			echo 'Fighters destroyed by beams ', $attackerfighterslost, '<br>';
    }
    else
    {
        if ($debug)
			echo 'pfigs ', $planetfighterslost, ' mefigs ', $attackerfighters, ' - ', $attackerfighterslost, '<br>';

        $attackerfighterslost += $planettorps * $torp_dmg_rate;

        if ($attackerfighters <= $attackerfighterslost)
            echo $txt['bnt_bigtorps'], '<br>';
        else
        {
            echo $txt['bnt_strafesuccess'], '<br>';
			
            if ($ownerfightercapacity / $attackerfightercapacity > 1)
            {
                $planetfighterslost = $attackerfighters - $attackerfighterslost;
                if ($debug)
					echo 'small guyfigs lost ', $planetfighterslost, '<br>';
            }
            else
            {
                $planetfighterslost = round(($attackerfighters - $attackerfighterslost) * $ownerfightercapacity / $attackerfightercapacity);
                if ($debug)
					echo 'bigguy figs lost ', $planetfighterslost, '<br>';
                if ($debug)
					echo 'which is ', $attackerfighters, '-', $attackerfighterslost, ' times ', $ownerfightercapacity, ' / ', $attackerfightercapacity, '<br>';
            }
            if ($planetfighterslost > $planetfighters)
                $planetfighterslost = $planetfighters;
        }
    }

    if ($debug)
		echo 'total figs lost ', $planetfighterslost, '<br>';
		
    echo '<br><br>';
	
	$update = $smcFunc['db_query']('', '
		UPDATE {raw:db_ships}
		SET turns = turns - 1, 
			turns_used = turns_used + 1, 
			ship_fighters = ship_fighters - {int:attackerfighters}
		WHERE ship_id = {int:ship_id}',
		array(
			'db_ships' => $dbtables['ships'],
			'attackerfighters' => $attackerfighters,
			'ship_id' => $playerinfo['ship_id']
		)
	);
	
	$update = $smcFunc['db_query']('', '
		UPDATE {raw:db_planets}
		SET energy = energy - {int:beamsused},
			fighters = fighters - {int:planetfighterslost},
			torps = torps - {int:planettorps}
		WHERE planet_id = {int:planet_id}',
		array(
			'db_planets' => $dbtables['planets'],
			'planet_id' => $planetinfo['planet_id'],
			'beamsused' => $beamsused,
			'planetfighterslost' => $planetfighterslost,
			'planettorps' => $planettorps
		)
	);
	
	$unlock = $smcFunc['db_query']('', 'UNLOCK TABLES');
	
	playerlog($ownerinfo['ship_id'], LOG_PLANET_BOMBED, "$planetinfo[name]|$playerinfo[sector]|$playerinfo[character_name]|$beamsused|$planettorps|$planetfighterslost");
}

function planetcombat($playerinfo,$ownerinfo,$sectorinfo,$planetinfo)
{
	global $smcFunc, $txt, $scripturl;

    global $torpedo_price;
    global $colonist_price;
    global $ore_price, $organics_price, $goods_price, $energy_price;

    global $torp_dmg_rate;
    global $level_factor, $upgrade_factor, $upgrade_cost;
    global $start_energy;
    global $min_value_capture;
    global $dbtables;
	global $debug;

    if ($playerinfo['turns'] < 1)
    {
        echo $txt['bnt_cmb_atleastoneturn'], '<br><br>';
        TextMainMenu();
        die();
    }

    // Planetary defense system calculation
    $planetbeams        = calcplanetbeams($playerinfo,$ownerinfo,$sectorinfo,$planetinfo);
    $planetfighters     = calcplanetfighters($planetinfo);
    $planetshields      = calcplanetshields($playerinfo,$ownerinfo,$sectorinfo,$planetinfo);
    $planettorps        = calcplanettorps($playerinfo,$ownerinfo,$sectorinfo,$planetinfo);

    // Attacking ship calculations
    $attackerbeams      = NUM_BEAMS($playerinfo['beams']);
    $attackerfighters   = $playerinfo['ship_fighters'];
    $attackershields    = NUM_SHIELDS($playerinfo['shields']);
    $attackertorps      = round(mypw($level_factor, $playerinfo['torp_launchers'])) * 2;
    $attackerarmor      = $playerinfo['armor_pts'];

    // Now modify player beams, shields and torpedos on available materiel
    $start_energy = $playerinfo['ship_energy'];

    // Beams
    if ($debug)
        echo $txt['bnt_cmb_shipenergybb'], ': ', $playerinfo['ship_energy'], '<br>';
    if ($attackerbeams > $playerinfo['ship_energy'])
        $attackerbeams = $playerinfo['ship_energy'];
    $playerinfo['ship_energy'] = $playerinfo['ship_energy'] - $attackerbeams;
    if ($debug)
        echo $txt['bnt_cmb_shipenergyab'], ' (before shields): ', $playerinfo['ship_energy'], '<br>';

    // Shields
    if ($attackershields > $playerinfo['ship_energy'])
        $attackershields = $playerinfo['ship_energy'];
    $playerinfo['ship_energy'] = $playerinfo['ship_energy'] - $attackershields;
    if ($debug)
        echo $txt['bnt_cmb_shipenergyas'], ': ', $playerinfo['ship_energy'], '<br>';

    // Torpedos
    if ($debug)
        echo $txt['bnt_cmb_shiptorpsbtl'], ': ', $attackertorps, ' (', $playerinfo['torps'], ' / ', $playerinfo['torp_launchers'], ')<br>';
    if ($attackertorps > $playerinfo['torps'])
        $attackertorps = $playerinfo['torps'];
    $playerinfo['torps'] = $playerinfo['torps'] - $attackertorps;
    if ($debug)
        echo $txt['bnt_cmb_shiptorpsatl'], ': ', $attackertorps, ' (', $playerinfo['torps'], ' / ', $playerinfo['torp_launchers'], ')<br>';

    // Setup torp damage rate for both Planet and Ship
    $planettorpdamage   = $torp_dmg_rate * $planettorps;
    $attackertorpdamage = $torp_dmg_rate * $attackertorps;
	
    if ($debug)
        echo $txt['bnt_cmb_planettorpdamage'], ': $planettorpdamage<br>';
    if ($debug)
        echo $txt['bnt_cmb_attackertorpdamage'], ': ', $attackertorpdamage, '<br>';


    echo '
		<center>
	    <hr>
	    <table width="75%" border="0">
		    <tr align="center">
			    <td width="9%" height="27"></td>
			    <td width="12%" height="27"><font color="white">', $txt['bnt_cmb_beams'], '</font></td>
			    <td width="17%" height="27"><font color="white">', $txt['bnt_cmb_fighters'], '</font></td>
			    <td width="18%" height="27"><font color="white">', $txt['bnt_cmb_shields'], '</font></td>
			    <td width="11%" height="27"><font color="white">', $txt['bnt_cmb_torps'], '</font></td>
			    <td width="22%" height="27"><font color="white">', $txt['bnt_cmb_torpdamage'], '</font></td>
			    <td width="11%" height="27"><font color="white">', $txt['bnt_cmb_armor'], '</font></td>
		    </tr>
		    <tr align="center">
			    <td width="9%"><font color="red">', $txt['bnt_cmb_you'], '</td>
			    <td width="12%"><font color="red"><b>', $attackerbeams, '</b></font></td>
			    <td width="17%"><font color="red"><b>', $attackerfighters, '</b></font></td>
			    <td width="18%"><font color="red"><b>', $attackershields, '</b></font></td>
			    <td width="11%"><font color="red"><b>', $attackertorps, '</b></font></td>
			    <td width="22%"><font color="red"><b>', $attackertorpdamage, '</b></font></td>
			    <td width="11%"><font color="red"><b>', $attackerarmor, '</b></font></td>
		    </tr>
		    <tr align="center">
			    <td width="9%"><font color="#6098f8">', $txt['bnt_cmb_planet'], '</font></td>
			    <td width="12%"><font color="#6098f8"><b>', $planetbeams, '</b></font></td>
			    <td width="17%"><font color="#6098f8"><b>', $planetfighters, '</b></font></td>
			    <td width="18%"><font color="#6098f8"><b>', $planetshields, '</b></font></td>
			    <td width="11%"><font color="#6098f8"><b>', $planettorps, '</b></font></td>
			    <td width="22%"><font color="#6098f8"><b>', $planettorpdamage, '</b></font></td>
			    <td width="11%"><font color="#6098f8"><b>n/a</b></font></td>
		    </tr>
	    </table>
	    <hr>
	    </center>';

    // Begin actual combat calculations
	
    $planetdestroyed   = 0;
    $attackerdestroyed = 0;

    echo '
		<br><center><b><font size="+2">', $txt['bnt_cmb_combatflow'], '</font></b><br><br>
		<table width="75%" border="0">
			<tr align="center">
				<td><font color="red">', $txt['bnt_cmb_you'], '</font></td>
				<td><font color="#6098f8">', $txt['bnt_cmb_defender'], '</font></td>
			</tr>
			<tr align="center">
				<td><font color="red"><b>', $txt['bnt_cmb_attackingplanet'], ' ', $playerinfo['sector'], '</b></font></td>
				<td></td>
			</tr>
			<tr align="center">
				<td><font color="red"><b>', $txt['bnt_cmb_youfireyourbeams'], '</b></font></td>
				<td></td>
			</tr>';
			
    if ($planetfighters > 0 && $attackerbeams > 0)
    {
        if ($attackerbeams > $planetfighters)
        {
            $txt['bnt_cmb_defenselost'] = str_replace("[cmb_planetfighters]", $planetfighters, $txt['bnt_cmb_defenselost']);
            echo '
			<tr align="center">
				<td></td>
				<td><font color="#6098f8"><b>', $txt['bnt_cmb_defenselost'], '</b></font></td>
			</tr>';
            $planetfighters = 0;
            $attackerbeams = $attackerbeams - $planetfighters;
        }
        else
        {
            $txt['bnt_cmb_defenselost2'] = str_replace("[cmb_attackerbeams]", $attackerbeams, $txt['bnt_cmb_defenselost2']);
            $planetfighters = $planetfighters - $attackerbeams;
            echo '
			<tr align="center">
				<td></td>
				<td><font color="#6098f8"><b>', $txt['bnt_cmb_defenselost2'], '</b></font></td>
			</tr>';
            $attackerbeams = 0;
        }
    }

    if ($attackerfighters > 0 && $planetbeams > 0)
    {
        // If there are more beams on the planet than attacker has fighters.
        if ($planetbeams > round($attackerfighters / 2))
        {
            // Half the attacker fighters
            $temp = round($attackerfighters / 2);
            // Attacker loses half his fighters
            $lost = $attackerfighters - $temp;
            // Set attacker fighters to 1/2 it's original value
            $attackerfighters = $temp;
            // Subtract half the attacker fighters from available planetary beams
            $planetbeams = $planetbeams - $lost;
			
            $txt['bnt_cmb_planetarybeams'] = str_replace("[cmb_temp]", $temp, $txt['bnt_cmb_planetarybeams']);
            echo '
			<tr align="center">
				<td></td>
				<td><font color="#6098F8"><b>', $txt['bnt_cmb_planetarybeams'], '</b></font></td>
			</tr>';
        }
        else
        {
            $txt['bnt_cmb_planetarybeams2'] = str_replace("[cmb_planetbeams]", $planetbeams, $txt['bnt_cmb_planetarybeams2']);
            $attackerfighters = $attackerfighters - $planetbeams;
			
            echo '
			<tr align="center">
				<td></td>
				<td><font color="#6098F8"><b>', $txt['bnt_cmb_planetarybeams2'], '</b></font></td>
			</tr>';
			
		   $planetbeams = 0;
        }
    }
	
    if ($attackerbeams > 0)
    {
        if ($attackerbeams > $planetshields)
        {
            $attackerbeams = $attackerbeams - $planetshields;
            $planetshields = 0;
            echo '
			<tr align="center">
				<td><font color="red"><b>', $txt['bnt_cmb_youdestroyedplanetshields'], '</b></font></td>
				<td></td>
			</tr>';
		}
        else
        {
			$txt['bnt_cmb_beamsexhausted'] = str_replace("[cmb_attackerbeams]", $attackerbeams, $txt['bnt_cmb_beamsexhausted']);
            echo '
			<tr align="center">
				<td><font color="red"><b>', $txt['bnt_cmb_beamsexhausted'], '</b></font></td>
				<td></td>
			</tr>';
           
		    $planetshields = $planetshields - $attackerbeams;
            $attackerbeams = 0;
        }
    }
	
    if ($planetbeams > 0)
    {
        if ($planetbeams > $attackershields)
        {
            $planetbeams = $planetbeams - $attackershields;
            $attackershields = 0;
            echo '
			<tr align="center">
				<td></td>
				<td><font color="#6098F8"><b>', $txt['bnt_cmb_breachedyourshields'], '</b></font></td>
			</tr>';
        }
        else
        {
            $attackershields = $attackershields - $planetbeams;
            $txt['bnt_cmb_destroyedyourshields'] = str_replace("[cmb_planetbeams]", $planetbeams, $txt['bnt_cmb_destroyedyourshields']);
            echo '
			<tr align="center">
				<td></td>
				<td><font color="#6098F8"><b>', $txt['bnt_cmb_destroyedyourshields'], '</b></font></td>
			</tr>';
			
			$planetbeams = 0;
        }
    }
	
    if ($planetbeams > 0)
    {
        if ($planetbeams > $attackerarmor)
        {
            $attackerarmor = 0;
            echo '
			<tr align="center">
				<td></td>
				<td><font color="#6098F8"><b>', $txt['bnt_cmb_breachedyourarmor'], '</b></font></td>
			</tr>';
        }
        else
        {
            $attackerarmor = $attackerarmor - $planetbeams;
            $txt['bnt_cmb_destroyedyourarmor'] = str_replace("[cmb_planetbeams]", $planetbeams, $txt['bnt_cmb_destroyedyourarmor']);
            echo '
			<tr align="center">
				<td></td>
				<td><font color="#6098F8"><b>', $txt['bnt_cmb_destroyedyourarmor'], '</b></font></td>
			</tr>';
        }
    }

	echo '
			<tr align="center">
				<td><font color="yellow"><b>', $txt['bnt_cmb_torpedoexchangephase'], '</b></font></td>
				<td><font color="yellow"><b>', $txt['bnt_cmb_torpedoexchangephase'], '</b></font></td>
			</tr>';
			
   	if ($planetfighters > 0 && $attackertorpdamage > 0)
    {
        if ($attackertorpdamage > $planetfighters)
        {
            $txt['bnt_cmb_nofightersleft'] = str_replace("[cmb_planetfighters]", $planetfighters,$txt['bnt_cmb_nofightersleft']);
            
			echo '
			<tr align="center">
				<td><font color="red"><b>', $txt['bnt_cmb_nofightersleft'], '</b></font></td>
				<td></td>
			</tr>';
			
			$planetfighters = 0;
            $attackertorpdamage = $attackertorpdamage - $planetfighters;
        }
        else
        {
            $planetfighters = $planetfighters - $attackertorpdamage;
			
            $txt['bnt_cmb_youdestroyfighters'] = str_replace("[cmb_attackertorpdamage]", $attackertorpdamage, $txt['bnt_cmb_youdestroyfighters']);
            
			echo '
			<tr align="center">
				<td><font color="red"><b>', $txt['bnt_cmb_youdestroyfighters'], '</b></font></td>
				<td></td>
			</tr>';
			
			$attackertorpdamage = 0;
        }
    }
	
    if ($attackerfighters > 0 && $planettorpdamage > 0)
    {
        if ($planettorpdamage > round($attackerfighters / 2))
        {
            $temp = round($attackerfighters / 2);
            $lost = $attackerfighters - $temp;
            $attackerfighters = $temp;
            $planettorpdamage = $planettorpdamage - $lost;
			
            $txt['bnt_cmb_planettorpsdestroy'] = str_replace("[cmb_temp]", $temp, $txt['bnt_cmb_planettorpsdestroy']);
			
			echo '
			<tr align="center">
				<td></td>
				<td><font color="#6098F8"><b>', $txt['bnt_cmb_planettorpsdestroy'], '</b></font></td>
			</tr>';
		}
        else
        {
            $attackerfighters = $attackerfighters - $planettorpdamage;
			
            $txt['bnt_cmb_planettorpsdestroy2'] = str_replace("[cmb_planettorpdamage]", $planettorpdamage, $txt['bnt_cmb_planettorpsdestroy2']);
			
			echo '
			<tr align="center">
				<td></td>
				<td><font color="#6098F8"><b>', $txt['bnt_cmb_planettorpsdestroy2'], '</b></font></td>
			</tr>';
		   
			$planettorpdamage = 0;
        }
    }
	
    if ($planettorpdamage > 0)
    {
        if ($planettorpdamage > $attackerarmor)
        {
            $attackerarmor = 0;
			
			echo '
			<tr align="center">
				<td><font color="#6098F8"><b>', $txt['bnt_cmb_torpsbreachedyourarmor'], '</b></font></td>
				<td></td>
			</tr>';
		}
        else
        {
            $attackerarmor = $attackerarmor - $planettorpdamage;
			
			$txt['bnt_cmb_planettorpsdestroy3'] = str_replace("[cmb_planettorpdamage]", $planettorpdamage, $txt['bnt_cmb_planettorpsdestroy3']);

			echo '
			<tr align="center">
				<td></td>
				<td><font color="#6098F8"><b>', $txt['bnt_cmb_planettorpsdestroy3'], '</b></font></td>
			</tr>';
		}
    }
	
    if ($attackertorpdamage > 0 && $planetfighters > 0)
    {
        $planetfighters = $planetfighters - $attackertorpdamage;
		
        if ($planetfighters < 0)
        {
            $planetfighters = 0;
			
			echo '
			<tr align="center">
				<td><font color="red"><b>', $txt['bnt_cmb_youdestroyedallfighters'], '</b></font></td>
				<td></td>
			</tr>';
        }
        else
        {
            $txt['bnt_cmb_youdestroyplanetfighters'] = str_replace("[cmb_attackertorpdamage]", $attackertorpdamage, $txt['bnt_cmb_youdestroyplanetfighters']);
			echo '
			<tr align="center">
				<td><font color="red"><b>', $txt['bnt_cmb_youdestroyplanetfighters'], '</b></font></td>
				<td></td>
			</tr>';
		}
    }
	
	echo '
			<tr align="center">
				<td><font color="yellow"><b>', $txt['bnt_cmb_fightercombatphase'], '</b></font></td>
				<td><font color="yellow"><b>', $txt['bnt_cmb_fightercombatphase'], '</b></font></td>
			</tr>';
			
	if ($attackerfighters > 0 && $planetfighters > 0)
	{
		if($attackerfighters > $planetfighters)
		{
			echo '
					<tr align="center">
						<td><font color="red"><b>', $txt['bnt_cmb_youdestroyedallfighters2'], '</b></font></td>
						<td></td>
					</tr>';
            $tempplanetfighters = 0;
        }
        else
        {
            $txt['bnt_cmb_youdestroyplanetfighters2'] = str_replace("[cmb_attackerfighters]", $attackerfighters, $txt['bnt_cmb_youdestroyplanetfighters2']);
			echo '
					<tr align="center">
						<td><font color="red"><b>', $txt['bnt_cmb_youdestroyplanetfighters2'], '</b></font></td>
						<td></td>
					</tr>';
			$tempplanetfighters = $planetfighters - $attackerfighters;
        }
		
        if ($planetfighters > $attackerfighters)
        {
			echo '
					<tr align="center">
						<td><font color="red"><b>', $txt['bnt_cmb_allyourfightersdestroyed'], '</b></font></td>
						<td></td>
					</tr>';
            $tempplayfighters = 0;
        }
        else
        {
            $tempplayfighters = $attackerfighters - $planetfighters;
            $txt['bnt_cmb_fightertofighterlost'] = str_replace("[cmb_planetfighters]", $planetfighters, $txt['bnt_cmb_fightertofighterlost']);
			echo '
					<tr align="center">
						<td><font color="red"><b>', $txt['bnt_cmb_fightertofighterlost'], '</b></font></td>
						<td></td>
					</tr>';
        }
		
        $attackerfighters = $tempplayfighters;
        $planetfighters = $tempplanetfighters;
    }
	
    if ($attackerfighters > 0 && $planetshields > 0)
    {
        if ($attackerfighters > $planetshields)
        {
            $attackerfighters = $attackerfighters - round($planetshields / 2);
			echo '
					<tr align="center">
						<td><font color="red"><b>', $txt['bnt_cmb_youbreachedplanetshields'], '</b></font></td>
						<td></td>
					</tr>';
            $planetshields = 0;
        }
        else
        {
            $txt['bnt_cmb_shieldsremainup'] = str_replace("[cmb_attackerfighters]", $attackerfighters, $txt['bnt_cmb_shieldsremainup']);
			echo '
					<tr align="center">
						<td></td>
						<td><font color="#6098F8"><b>', $txt['bnt_cmb_shieldsremainup'], '</b></font></td>
					</tr>';
            $planetshields = $planetshields - $attackerfighters;
        }
    }
	
    if ($planetfighters > 0)
    {
        if ($planetfighters > $attackerarmor)
        {
            $attackerarmor = 0;
			echo '
					<tr align="center">
						<td><font color="red"><b>', $txt['bnt_cmb_fighterswarm'], '</b></font></td>
						<td></td>
					</tr>';
        }
        else
        {
            $attackerarmor = $attackerarmor - $planetfighters;
			echo '
					<tr align="center">
						<td><font color="red"><b>', $txt['bnt_cmb_swarmandrepel'], '</b></font></td>
						<td></td>
					</tr>';
        }
    }

    echo '</table></center>';
	
    // Send each docked ship in sequence to attack agressor
	$result = $smcFunc['db_query']('', '
		SELECT *
		FROM {raw:db_ships}
		WHERE on_planet = "Y"
		AND planet_id = {raw:planet_id}',
		array(
			'db_ships' => $dbtables['ships'],
			'planet_id' => $planetinfo['planet_id']
		)
	);
    $shipsonplanet = $smcFunc['db_num_rows']($result);

    if ($shipsonplanet > 0)
    {
        $txt['bnt_cmb_shipdock'] = str_replace("[cmb_shipsonplanet]", $shipsonplanet, $txt['bnt_cmb_shipdock']);
        echo '<br><br><center>', $txt['bnt_cmb_shipdock'], '<br>', $txt['bnt_cmb_engshiptoshipcombat'], '</center><br><br>';
		
        while ($onplanet = $smcFunc['db_fetch_assoc']($result))
        {
            if ($attackerfighters < 0)
                $attackerfighters = 0;
            if ($attackertorps    < 0)
                $attackertorps = 0;
            if ($attackershields  < 0)
                $attackershields = 0;
            if ($attackerbeams    < 0)
                $attackerbeams = 0;
            if ($attackerarmor    < 1)
                break;

            echo '<br>-', $onplanet['ship_name'], ' ', $txt['bnt_cmb_approachattackvector'], '-<br>';
            shiptoship($onplanet['ship_id'],$playerinfo,$attackerfighters,$attackertorpdamage,$attackershields,$attackerbeams,$attackerarmor,$attackertorps);
        }
    }
    else
        echo '<br><br><center>', $txt['bnt_cmb_noshipsdocked'], '</center><br><br>';
	
	$smcFunc['db_free_result']($result);
	
    if ($attackerarmor < 1)
    {
        $free_ore = round($playerinfo['ship_ore'] / 2);
        $free_organics = round($playerinfo['ship_organics'] / 2);
        $free_goods = round($playerinfo['ship_goods'] / 2);
        $ship_value = $upgrade_cost * (round(mypw($upgrade_factor, $playerinfo['hull'])) + round(mypw($upgrade_factor, $playerinfo['engines'])) + round(mypw($upgrade_factor, $playerinfo['power'])) + round(mypw($upgrade_factor, $playerinfo['computer'])) + round(mypw($upgrade_factor, $playerinfo['sensors'])) + round(mypw($upgrade_factor, $playerinfo['beams'])) + round(mypw($upgrade_factor, $playerinfo['torp_launchers'])) + round(mypw($upgrade_factor, $playerinfo['shields'])) + round(mypw($upgrade_factor, $playerinfo['armor'])) + round(mypw($upgrade_factor, $playerinfo['cloak'])));
        $ship_salvage_rate = rand(0,10);
        $ship_salvage = $ship_value * $ship_salvage_rate / 100;
		
        echo '<br><center><font size="+2" color="red"><b>', $txt['bnt_cmb_yourshipdestroyed'], '</font></b></center><br>';
        if ($playerinfo['dev_escapepod'] == "Y")
        {
            echo '<center><font color="white">', $txt['bnt_cmb_escapepod'], '</font></center><br><br>';
			$update = $smcFunc['db_query']('', '
				UPDATE {raw:db_ships}
				SET hull = 0,
					engines = 0,
					power = 0,
					sensors = 0,
					computer = 0,
					beams = 0,
					torp_launchers = 0,
					torps = 0,
					armor = 0,
					armor_pts = 100,
					cloak = 0,
					shields = 0,
					sector = 0,
					ship_organics = 0,
					ship_ore = 0,
					ship_goods = 0,
					ship_energy = {int:start_energy},
					ship_colonists = 0,
					ship_fighters = 100,
					dev_warpedit = 0,
					dev_genesis = 0,
					dev_beacon = 0,
					dev_emerwarp = 0,
					dev_escapepod = "N",
					dev_fuelscoop = "N",
					dev_minedeflector = 0,
					on_planet = "N",
					cleared_defences = NULL,
					dev_lssd = "N"
				WHERE ship_id = {int:ship_id}',
				array(
					'db_ships' => $dbtables['ships'],
					'ship_id' => $playerinfo['ship_id'],
					'start_energy' => $start_energy,
				)
			);
            collect_bounty($planetinfo['owner'],$playerinfo['ship_id']);
        }
        else
        {
            db_kill_player($playerinfo['ship_id']);
            collect_bounty($planetinfo['owner'],$playerinfo['ship_id']);
        }
    }
    else
    {
        $free_ore = 0;
        $free_goods = 0;
        $free_organics = 0;
        $ship_salvage_rate = 0;
        $ship_salvage = 0;
        
		$planetrating = $ownerinfo['hull'] + $ownerinfo['engines'] + $ownerinfo['computer'] + $ownerinfo['beams'] + $ownerinfo['torp_launchers'] + $ownerinfo['shields'] + $ownerinfo['armor'];
        
		if ($ownerinfo['rating'] != 0)
            $rating_change = ($ownerinfo['rating'] / abs($ownerinfo['rating'])) * $planetrating * 10;
        else
            $rating_change = -100;
        
		echo '<center><br><b><font size="+2">', $txt['bnt_cmb_finalcombatstats'], '</font></b><br><br>';
        
		$fighters_lost = $playerinfo['ship_fighters'] - $attackerfighters;
        $txt['bnt_cmb_youlostfighters'] = str_replace("[cmb_fighters_lost]", $fighters_lost, $txt['bnt_cmb_youlostfighters']);
        $txt['bnt_cmb_youlostfighters'] = str_replace("[cmb_playerinfo_ship_fighters]", $playerinfo['ship_fighters'], $txt['bnt_cmb_youlostfighters']);
        echo $txt['bnt_cmb_youlostfighters'], '<br>';
		
        $armor_lost = $playerinfo['armor_pts'] - $attackerarmor;
        $txt['bnt_cmb_youlostarmorpoints'] = str_replace("[cmb_armor_lost]", $armor_lost, $txt['bnt_cmb_youlostarmorpoints']);
        $txt['bnt_cmb_youlostarmorpoints'] = str_replace("[cmb_playerinfo_armor_pts]", $playerinfo['armor_pts'], $txt['bnt_cmb_youlostarmorpoints']);
        $txt['bnt_cmb_youlostarmorpoints'] = str_replace("[cmb_attackerarmor]", $attackerarmor, $txt['bnt_cmb_youlostarmorpoints']);
        echo $txt['bnt_cmb_youlostarmorpoints'], '<br>';
        
		$energy = $playerinfo['ship_energy'];
        $energy_lost = $start_energy - $playerinfo['ship_energy'];
		$txt['bnt_cmb_energyused'] = str_replace("[cmb_energy_lost]", $energy_lost, $txt['bnt_cmb_energyused']);
        $txt['bnt_cmb_energyused'] = str_replace("[cmb_playerinfo_ship_energy]", $start_energy, $txt['bnt_cmb_energyused']);
        echo $txt['bnt_cmb_energyused'], '<br></CENTER>';
        
		$update = $smcFunc['db_query']('', '
			UPDATE {raw:db_ships}
			SET ship_energy = {int:energy},
				ship_fighters = ship_fighters - {int:fighters_lost},
				armor_pts = armor_pts - {int:armor_lost}, 
				torps = torps - {int:attackertorps},
				rating = rating - {int:rating_change} 
			WHERE ship_id = {int:ship_id}',
			array(
				'db_ships' => $dbtables['ships'],
				'ship_id' => $playerinfo['ship_id'],
				'energy' => $energy,
				'fighters_lost' => $fighters_lost,
				'armor_lost' => $armor_lost,
				'attackertorps' => $attackertorps,
				'rating_change' => $rating_change
			)
		);
    }
	
	$result = $smcFunc['db_query']('', '
		SELECT *
		FROM {raw:db_ships}
		WHERE on_planet = "Y"
		AND planet_id = {raw:planet_id}',
		array(
			'db_ships' => $dbtables['ships'],
			'planet_id' => $planetinfo['planet_id']
		)
	);
	
    $shipsonplanet = $smcFunc['db_num_rows']($result);
	$smcFunc['db_free_result']($result);
	
    if ($planetshields < 1 && $planetfighters < 1 && $attackerarmor > 0 && $shipsonplanet == 0)
    {
        echo '<br><br><center><font color="green"><b>', $txt['bnt_cmb_planetdefeated'], '</b></font></center><br><br>';

        if ($min_value_capture != 0)
        {
            $playerscore = gen_score($playerinfo['ship_id']);
            $playerscore *= $playerscore;

            $planetscore = $planetinfo['organics'] * $organics_price + $planetinfo['ore'] * $ore_price + $planetinfo['goods'] * $goods_price + $planetinfo['energy'] * $energy_price + $planetinfo['fighters'] * $fighter_price + $planetinfo['torps'] * $torpedo_price + $planetinfo['colonists'] * $colonist_price + $planetinfo['credits'];
            $planetscore = $planetscore * $min_value_capture / 100;

            if ($playerscore < $planetscore)
            {
                echo '<center>' ,$txt['bnt_cmb_citizenswanttodie'], '</center><br><br>';
                
				$delete = $smcFunc['db_query']('', '
					DELETE FROM {raw:db_planets}
					WHERE planet_id = {raw:planet_id}',
					array(
						'db_planets' => $dbtables['planets'],
						'planet_id' => $planetinfo['planet_id']
					)
				);
				playerlog($ownerinfo['ship_id'], LOG_PLANET_DEFEATED_D, "$planetinfo[name]|$playerinfo[sector]|$playerinfo[character_name]");
                adminlog(LOG_ADMIN_PLANETDEL, "$playerinfo[character_name]|$ownerinfo[character_name]|$playerinfo[sector]");
                gen_score($ownerinfo['ship_id']);
            }
            else
            {
                $txt['bnt_cmb_youmaycapture'] = str_replace("[cmb_planetinfo_planet_id]", $planetinfo['planet_id'], $txt['bnt_cmb_youmaycapture']);
				echo '<center><font color="red">', $txt['bnt_cmb_youmaycapture'], '</font></center><br><br>';
                
				playerlog($ownerinfo['ship_id'], LOG_PLANET_DEFEATED, "$planetinfo[name]|$playerinfo[sector]|$playerinfo[character_name]");
                gen_score($ownerinfo['ship_id']);
				
				$update = $smcFunc['db_query']('', '
					UPDATE {raw:db_planets}
					SET owner = 0,
						fighters = 0,
						torps = torps - {int:planettorps},
						base = "N",
						defeated = "Y"
					WHERE planet_id = {raw:planet_id}',
					array(
						'db_planets' => $dbtables['planets'],
						'planet_id' => $planetinfo['planet_id'],
						'planettorps' => $planettorps
					)
				);
            }
        }
        else
        {
            $txt['bnt_cmb_youmaycapture2'] = str_replace("[cmb_planetinfo_planet_id]", $planetinfo['planet_id'], $txt['bnt_cmb_youmaycapture2']);
            echo '<center>', $txt['bnt_cmb_youmaycapture2'], '</center><br><br>';
            
			playerlog($ownerinfo['ship_id'], LOG_PLANET_DEFEATED, "$planetinfo[name]|$playerinfo[sector]|$playerinfo[character_name]");
            gen_score($ownerinfo['ship_id']);
			
			$update = $smcFunc['db_query']('', '
				UPDATE {raw:db_planets}
				SET owner = 0,
					fighters = 0,
					torps = torps - {int:planettorps},
					base = "N",
					defeated = "Y"
				WHERE planet_id = {raw:planet_id}',
				array(
					'db_planets' => $dbtables['planets'],
					'planet_id' => $planetinfo['planet_id'],
					'planettorps' => $planettorps
				)
			);
		}
        calc_ownership($planetinfo['sector_id']);
    }
    else
    {
        echo '<br><br><center><font color="#6098f8"><b>', $txt['bnt_cmb_planetnotdefeated'], '</b></font></center><br><br>';
        
		if ($debug)
            echo '<br><br>', $txt['bnt_cmb_planetstatistics'], '<br><br>';
        $fighters_lost = $planetinfo['fighters'] - $planetfighters;
        $txt['bnt_cmb_fighterloststat'] = str_replace("[cmb_fighters_lost]", $fighters_lost, $txt['bnt_cmb_fighterloststat']);
        $txt['bnt_cmb_fighterloststat'] = str_replace("[cmb_planetinfo_fighters]", $planetinfo['fighters'], $txt['bnt_cmb_fighterloststat']);
        $txt['bnt_cmb_fighterloststat'] = str_replace("[cmb_planetfighters]", $planetfighters, $txt['bnt_cmb_fighterloststat']);
        if ($debug)
            echo $txt['bnt_cmb_fighterloststat'], '<br>';
			
        $energy = $planetinfo['energy'];
        if ($debug)
            echo $txt['bnt_cmb_energyleft'], ': ', $planetinfo['energy'], '<br>';
        
		playerlog($ownerinfo['ship_id'], LOG_PLANET_NOT_DEFEATED, "$planetinfo[name]|$playerinfo[sector]|$playerinfo[character_name]|$free_ore|$free_organics|$free_goods|$ship_salvage_rate|$ship_salvage");
        gen_score($ownerinfo['ship_id']);

		$update = $smcFunc['db_query']('', '
			UPDATE {raw:db_planets}
			SET energy = {int:energy},
				fighters = fighters - {int:fighters_lost},
				torps = torps - {int:planettorps}, 
				ore = ore + {int:free_ore},
				goods = goods + {int:free_goods},
				organics = organics + {int:free_organics},
				credits = credits + {float:ship_salvage}
			WHERE planet_id = {raw:planet_id}',
			array(
				'db_planets' => $dbtables['planets'],
				'planet_id' => $planetinfo['planet_id'],
				'energy' => $energy,
				'fighters_lost' => $fighters_lost,
				'planettorps' => $planettorps,
				'free_ore' => $free_ore,
				'free_goods' => $free_goods,
				'free_organics' => $free_organics,
				'ship_salvage' => $ship_salvage,
			)
		);
        if ($debug)
            echo '<br>Set: energy=', $energy, ', fighters lost=', $fighters_lost,', torps=', $planetinfo['torps'], ', sectorid=', $sectorinfo['sector_id'], '<br>';
    }
	$update = $smcFunc['db_query']('', '
		UPDATE {raw:db_ships}
		SET turns = turns - 1,
			turns_used = turns_used + 1
		WHERE ship_id = {int:ship_id}',
		array(
			'db_ships' => $dbtables['ships'],
			'ship_id' => $playerinfo['ship_id']
		)
	);
}

function shiptoship($ship_id,$playerinfo,$attackerfighters,$attackertorpdamage,$attackershields,$attackerbeams,$attackerarmor,$attackertorps)
{
    global $smcFunc, $txt;
	global $start_energy, $level_factor, $torp_dmg_rate, $rating_combat_factor;
	global $upgrade_factor, $upgrade_cost;
    global $dbtables;
	
	/*
	$lock = $smcFunc['db_query']('', '
		LOCK TABLES
		{raw:db_ships} WRITE,
		{raw:db_universe} WRITE,
		{raw:db_zones} READ,
		{raw:db_logs} WRITE,
		{raw:db_bounty} WRITE,
		{raw:db_planets} WRITE,
		{raw:db_sector_defence} WRITE,
		{raw:db_news} WRITE',
		array(
			'db_ships' => $dbtables['ships'],
			'db_universe' => $dbtables['universe'],
			'db_zones' => $dbtables['zones'],
			'db_logs' => $dbtables['logs'],
			'db_bounty' => $dbtables['bounty'],
			'db_planets' => $dbtables['planets'],
			'db_sector_defence' => $dbtables['sector_defence'],
			'db_news' => $dbtables['news']
		)
	);
	*/
	
	$result = $smcFunc['db_query']('', '
		SELECT *
		FROM {raw:db_ships}
		WHERE ship_id = {int:ship_id}',
		array(
			'db_ships' => $dbtables['ships'],
			'ship_id' => $ship_id
		)
	);
    $targetinfo = $smcFunc['db_fetch_assoc']($result);
	$smcFunc['db_free_result']($result);

    echo '
	<br><br>-=-=-=-=-=-=-=--<br>
    ', $txt['bnt_cmb_startingstats'], ':<br><br>
    ', $txt['bnt_cmb_statattackerbeams'], ': ', $attackerbeams, '<br>
    ', $txt['bnt_cmb_statattackerfighters'], ': ', $attackerfighters, '<br>
    ', $txt['bnt_cmb_statattackershields'], ': ', $attackershields, '<br>
    ', $txt['bnt_cmb_statattackertorps'], ': ', $attackertorps, '<br>
    ', $txt['bnt_cmb_statattackerarmor'], ': ', $attackerarmor, '<br>
    ', $txt['bnt_cmb_statattackertorpdamage'], ': ', $attackertorpdamage, '<br>';

    $targetbeams = NUM_BEAMS($targetinfo['beams']);
    if ($targetbeams > $targetinfo['ship_energy'])
        $targetbeams = $targetinfo['ship_energy'];
    $targetinfo['ship_energy'] = $targetinfo['ship_energy'] - $targetbeams;
    $targetshields = NUM_SHIELDS($targetinfo['shields']);
	
    if ($targetshields > $targetinfo['ship_energy'])
        $targetshields=$targetinfo['ship_energy'];
    $targetinfo['ship_energy'] = $targetinfo['ship_energy'] - $targetshields;

    $targettorpnum = round(mypw($level_factor,$targetinfo['torp_launchers'])) * 2;
    if($targettorpnum > $targetinfo['torps'])
    {
        $targettorpnum = $targetinfo['torps'];
    }
    $targettorpdmg = $torp_dmg_rate * $targettorpnum;
	
    $targetarmor = $targetinfo['armor_pts'];
	
    $targetfighters = $targetinfo['ship_fighters'];
	
    $targetdestroyed = 0;
    $playerdestroyed = 0;
	
    echo '
	-->', $targetinfo['ship_name'], ' ', $txt['bnt_cmb_isattackingyou'], '<br><br>
    ', $txt['bnt_cmb_beamexchange'], '<br>';
	
    if ($targetfighters > 0 && $attackerbeams > 0)
    {
        if ($attackerbeams > round($targetfighters / 2))
        {
            $temp = round($targetfighters/2);
            $lost = $targetfighters - $temp;
            $targetfighters = $temp;
            $attackerbeams = $attackerbeams - $lost;
            $txt['bnt_cmb_beamsdestroy'] = str_replace("[cmb_lost]", $lost, $txt['bnt_cmb_beamsdestroy']);
            echo ' <-- ', $txt['bnt_cmb_beamsdestroy'], '<br>';
        }
        else
        {
            $targetfighters = $targetfighters - $attackerbeams;
            $txt['bnt_cmb_beamsdestroy2'] = str_replace("[cmb_attackerbeams]", $attackerbeams, $txt['bnt_cmb_beamsdestroy2']);
            echo '--> ', $txt['bnt_cmb_beamsdestroy2'], '<br>';
            $attackerbeams = 0;
        }
    }
    elseif ($targetfighters > 0 && $attackerbeams < 1)
		echo $txt['bnt_cmb_nobeamsareleft'], '<br>';
    else
        echo $txt['bnt_cmb_beamshavenotarget'], '<br>';
		
    if ($attackerfighters > 0 && $targetbeams > 0)
    {
        if ($targetbeams > round($attackerfighters / 2))
        {
            $temp = round($attackerfighters / 2);
            $lost = $attackerfighters - $temp;
            $attackerfighters = $temp;
            $targetbeams = $targetbeams - $lost;
            $txt['bnt_cmb_fighterdestroyedbybeams'] = str_replace("[cmb_targetinfo_ship_name]", $targetinfo['ship_name'], $txt['bnt_cmb_fighterdestroyedbybeams']);
            $txt['bnt_cmb_fighterdestroyedbybeams'] = str_replace("[cmb_lost]", $lost, $txt['bnt_cmb_fighterdestroyedbybeams']);
            echo '-->', $txt['bnt_cmb_fighterdestroyedbybeams'];
        }
        else
        {
            $attackerfighters = $attackerfighters - $targetbeams;
            $txt['bnt_cmb_beamsdestroystillhave'] = str_replace("[cmb_targetinfo_ship_name]", $targetinfo['ship_name'], $txt['bnt_cmb_beamsdestroystillhave']);
            $txt['bnt_cmb_beamsdestroystillhave'] = str_replace("[cmb_targetbeams]", $targetbeams, $txt['bnt_cmb_beamsdestroystillhave']);
            $txt['bnt_cmb_beamsdestroystillhave'] = str_replace("[cmb_attackerfighters]", $attackerfighters, $txt['bnt_cmb_beamsdestroystillhave']);
            echo '<-- ', $txt['bnt_cmb_beamsdestroystillhave'], '<br>';
            $targetbeams = 0;
        }
    }
    elseif ($attackerfighters > 0 && $targetbeams < 1)
		echo $txt['bnt_cmb_fighterunhindered'], '<br>';
    else
        echo $txt['bnt_cmb_youhavenofightersleft'], '<br>';
		
    if ($attackerbeams > 0)
    {
        if ($attackerbeams > $targetshields)
        {
            $attackerbeams = $attackerbeams - $targetshields;
            $targetshields = 0;
            $txt['bnt_cmb_breachedsomeshields'] = str_replace("[cmb_targetinfo_ship_name]", $targetinfo['ship_name'], $txt['bnt_cmb_breachedsomeshields']);
            echo '<-- ', $txt['bnt_cmb_breachedsomeshields'], '<br>';
        }
        else
        {
            $txt['bnt_cmb_shieldsarehitbybeam'] = str_replace("[cmb_targetinfo_ship_name]", $targetinfo['ship_name'], $txt['bnt_cmb_shieldsarehitbybeam']);
            $txt['bnt_cmb_shieldsarehitbybeam'] = str_replace("[cmb_attackerbeams]", $attackerbeams, $txt['bnt_cmb_shieldsarehitbybeam']);
            echo $txt['bnt_cmb_shieldsarehitbybeam'], '<br>';
            $targetshields = $targetshields - $attackerbeams;
            $attackerbeams = 0;
        }
    }
    else
    {
        $txt['bnt_cmb_nobeamslefttoattack'] = str_replace("[cmb_targetinfo_ship_name]", $targetinfo['ship_name'], $txt['bnt_cmb_nobeamslefttoattack']);
        echo $txt['bnt_cmb_nobeamslefttoattack'], '<br>';
    }
	
    if($targetbeams > 0)
    {
        if ($targetbeams > $attackershields)
        {
            $targetbeams = $targetbeams - $attackershields;
            $attackershields = 0;
            $txt['bnt_cmb_yourshieldsbreachedby'] = str_replace("[cmb_targetinfo_ship_name]", $targetinfo['ship_name'], $txt['bnt_cmb_yourshieldsbreachedby']);
            echo '--> ', $txt['bnt_cmb_yourshieldsbreachedby'], '<br>';
        }
        else
        {
            $txt['bnt_cmb_yourshieldsarehit'] = str_replace("[cmb_targetinfo_ship_name]", $targetinfo['ship_name'], $txt['bnt_cmb_yourshieldsarehit']);
            $txt['bnt_cmb_yourshieldsarehit'] = str_replace("[cmb_targetbeams]", $targetbeams, $txt['bnt_cmb_yourshieldsarehit']);
            echo '<-- ', $txt['bnt_cmb_yourshieldsarehit'], '<br>';
            $attackershields = $attackershields - $targetbeams;
            $targetbeams = 0;
        }
    }
    else
    {
        $txt['bnt_cmb_hehasnobeamslefttoattack'] = str_replace("[cmb_targetinfo_ship_name]", $targetinfo['ship_name'], $txt['bnt_cmb_hehasnobeamslefttoattack']);
        echo $txt['bnt_cmb_hehasnobeamslefttoattack'], '<br>';
    }
	
    if ($attackerbeams > 0)
    {
        if ($attackerbeams > $targetarmor)
        {
            $targetarmor = 0;
            $txt['bnt_cmb_yourbeamsbreachedhim'] = str_replace("[cmb_targetinfo_ship_name]", $targetinfo['ship_name'], $txt['bnt_cmb_yourbeamsbreachedhim']);
            echo '--> ', $txt['bnt_cmb_yourbeamsbreachedhim'], '<br>';
        }
        else
        {
            $targetarmor = $targetarmor - $attackerbeams;
            $txt['bnt_cmb_yourbeamshavedonedamage'] = str_replace("[cmb_attackerbeams]", $attackerbeams, $txt['bnt_cmb_yourbeamshavedonedamage']);
            $txt['bnt_cmb_yourbeamshavedonedamage'] = str_replace("[cmb_targetinfo_ship_name]", $targetinfo['ship_name'], $txt['bnt_cmb_yourbeamshavedonedamage']);
            echo $txt['bnt_cmb_yourbeamshavedonedamage'], '<br>';
        }
    }
    else
    {
        $txt['bnt_cmb_nobeamstoattackarmor'] = str_replace("[cmb_targetinfo_ship_name]", $targetinfo['ship_name'], $txt['bnt_cmb_nobeamstoattackarmor']);
        echo $txt['bnt_cmb_nobeamstoattackarmor'], '<br>';
    }
	
    if ($targetbeams > 0)
    {
        if ($targetbeams > $attackerarmor)
        {
            $attackerarmor = 0;
            $txt['bnt_cmb_yourarmorbreachedbybeams'] = str_replace("[cmb_targetinfo_ship_name]", $targetinfo['ship_name'], $txt['bnt_cmb_yourarmorbreachedbybeams']);
            echo '--> ', $txt['bnt_cmb_yourarmorbreachedbybeams'], '<br>';
        }
        else
        {
            $attackerarmor = $attackerarmor - $targetbeams;
            $txt['bnt_cmb_yourarmorhitdamaged'] = str_replace("[cmb_targetinfo_ship_name]", $targetinfo['ship_name'], $txt['bnt_cmb_yourarmorhitdamaged']);
            $txt['bnt_cmb_yourarmorhitdamaged'] = str_replace("[cmb_targetbeams]", $targetbeams, $txt['bnt_cmb_yourarmorhitdamaged']);
            echo '<-- ', $txt['bnt_cmb_yourarmorhitdamaged'], '<br>';
        }
    }
    else
    {
        $txt['bnt_cmb_hehasnobeamslefttoattackyou'] = str_replace("[cmb_targetinfo_ship_name]", $targetinfo['ship_name'], $txt['bnt_cmb_hehasnobeamslefttoattackyou']);
        echo $txt['bnt_cmb_hehasnobeamslefttoattackyou'], '<br>';
    }
	
    echo '<br>', $txt['bnt_cmb_torpedoexchange'], '<br>';
	
    if ($targetfighters > 0 && $attackertorpdamage > 0)
    {
        if ($attackertorpdamage > round($targetfighters / 2))
        {
            $temp = round($targetfighters / 2);
            $lost = $targetfighters - $temp;
            $targetfighters = $temp;
            $attackertorpdamage = $attackertorpdamage-$lost;
            $txt['bnt_cmb_yourtorpsdestroy'] = str_replace("[cmb_targetinfo_ship_name]", $targetinfo['ship_name'], $txt['bnt_cmb_yourtorpsdestroy']);
            $txt['bnt_cmb_yourtorpsdestroy'] = str_replace("[cmb_lost]", $lost, $txt['bnt_cmb_yourtorpsdestroy']);
            echo '--> ', $txt['bnt_cmb_yourtorpsdestroy'], '<br>';
        }
        else
        {
            $targetfighters = $targetfighters-$attackertorpdamage;
            $txt['bnt_cmb_yourtorpsdestroy2'] = str_replace("[cmb_targetinfo_ship_name]", $targetinfo['ship_name'], $txt['bnt_cmb_yourtorpsdestroy2']);
            $txt['bnt_cmb_yourtorpsdestroy2'] = str_replace("[cmb_attackertorpdamage]", $attackertorpdamage, $txt['bnt_cmb_yourtorpsdestroy2']);
            echo '<-- ', $txt['bnt_cmb_yourtorpsdestroy2'], '<br>';
            $attackertorpdamage = 0;
        }
    }
    elseif ($targetfighters > 0 && $attackertorpdamage < 1)
    {
        $txt['bnt_cmb_youhavenotorpsleft'] = str_replace("[cmb_targetinfo_ship_name]", $targetinfo['ship_name'], $txt['bnt_cmb_youhavenotorpsleft']);
        echo $txt['bnt_cmb_youhavenotorpsleft'], '<br>';
    }
    else
    {
        $txt['bnt_cmb_hehasnofighterleft'] = str_replace("[cmb_targetinfo_ship_name]", $targetinfo['ship_name'], $txt['bnt_cmb_hehasnofighterleft']);
        echo $txt['bnt_cmb_hehasnofighterleft'], '<br>';
    }
	
    if ($attackerfighters > 0 && $targettorpdmg > 0)
    {
        if ($targettorpdmg > round($attackerfighters / 2))
        {
            $temp = round($attackerfighters /2 );
            $lost = $attackerfighters - $temp;
            $attackerfighters = $temp;
            $targettorpdmg = $targettorpdmg - $lost;
            $txt['bnt_cmb_torpsdestroyyou'] = str_replace("[cmb_targetinfo_ship_name]", $targetinfo['ship_name'], $txt['bnt_cmb_torpsdestroyyou']);
            $txt['bnt_cmb_torpsdestroyyou'] = str_replace("[cmb_lost]", $lost, $txt['bnt_cmb_torpsdestroyyou']);
            echo '--> ', $txt['bnt_cmb_torpsdestroyyou'], '<br>';
        }
        else
        {
            $attackerfighters = $attackerfighters-$targettorpdmg;
            $txt['bnt_cmb_someonedestroyedfighters'] = str_replace("[cmb_targetinfo_ship_name]", $targetinfo['ship_name'], $txt['bnt_cmb_someonedestroyedfighters']);
            $txt['bnt_cmb_someonedestroyedfighters'] = str_replace("[cmb_targettorpdmg]", $targettorpdmg, $txt['bnt_cmb_someonedestroyedfighters']);
            echo '<-- ', $txt['bnt_cmb_someonedestroyedfighters'], '<br>';
            $targettorpdmg = 0;
        }
    }
    elseif ($attackerfighters > 0 && $targettorpdmg < 1)
    {
        $txt['bnt_cmb_hehasnotorpsleftforyou'] = str_replace("[cmb_targetinfo_ship_name]", $targetinfo['ship_name'], $txt['bnt_cmb_hehasnotorpsleftforyou']);
        echo $txt['bnt_cmb_hehasnotorpsleftforyou'], '<br>';
    }
    else
    {
        $txt['bnt_cmb_youhavenofightersanymore'] = str_replace("[cmb_targetinfo_ship_name]", $targetinfo['ship_name'], $txt['bnt_cmb_youhavenofightersanymore']);
        echo $txt['bnt_cmb_youhavenofightersanymore'], '<br>';
    }
	
    if ($attackertorpdamage > 0)
    {
        if ($attackertorpdamage > $targetarmor)
        {
            $targetarmor = 0;
            $txt['bnt_cmb_youbreachedwithtorps'] = str_replace("[cmb_targetinfo_ship_name]", $targetinfo['ship_name'], $txt['bnt_cmb_youbreachedwithtorps']);
            echo '--> ', $txt['bnt_cmb_youbreachedwithtorps'], '<br>';
        }
        else
        {
            $targetarmor = $targetarmor - $attackertorpdamage;
            $txt['bnt_cmb_hisarmorishitbytorps'] = str_replace("[cmb_targetinfo_ship_name]", $targetinfo['ship_name'], $txt['bnt_cmb_hisarmorishitbytorps']);
            $txt['bnt_cmb_hisarmorishitbytorps'] = str_replace("[cmb_attackertorpdamage]", $attackertorpdamage, $txt['bnt_cmb_hisarmorishitbytorps']);
            echo '<-- ', $txt['bnt_cmb_hisarmorishitbytorps'], '<br>';
        }
    }
    else
    {
        $txt['bnt_cmb_notorpslefttoattackarmor'] = str_replace("[cmb_targetinfo_ship_name]", $targetinfo['ship_name'], $txt['bnt_cmb_notorpslefttoattackarmor']);
        echo $txt['bnt_cmb_notorpslefttoattackarmor'], '<br>';
    }
	
    if ($targettorpdmg > 0)
    {
        if ($targettorpdmg > $attackerarmor)
        {
            $attackerarmor = 0;
            $txt['bnt_cmb_yourarmorbreachedbytorps'] = str_replace("[cmb_targetinfo_ship_name]", $targetinfo['ship_name'], $txt['bnt_cmb_yourarmorbreachedbytorps']);
            echo '<-- ', $txt['bnt_cmb_yourarmorbreachedbytorps'], '<br>';
        }
        else
        {
            $attackerarmor = $attackerarmor - $targettorpdmg;
            $txt['bnt_cmb_yourarmorhitdmgtorps'] = str_replace("[cmb_targettorpdmg]", $targettorpdmg, $txt['bnt_cmb_yourarmorhitdmgtorps']);
            $txt['bnt_cmb_yourarmorhitdmgtorps'] = str_replace("[cmb_targetinfo_ship_name]", $targetinfo['ship_name'], $txt['bnt_cmb_yourarmorhitdmgtorps']);
            echo '<-- ', $txt['bnt_cmb_yourarmorhitdmgtorps'], '<br>';
        }
    }
    else
    {
        $txt['bnt_cmb_hehasnotorpsforyourarmor'] = str_replace("[cmb_targetinfo_ship_name]", $targetinfo['ship_name'], $txt['bnt_cmb_hehasnotorpsforyourarmor']);
        echo $txt['bnt_cmb_hehasnotorpsforyourarmor'], '<br>';
    }
	
    echo '<br>', $txt['bnt_cmb_fightersattackexchange'], '<br>';
	
    if ($attackerfighters > 0 && $targetfighters > 0)
    {
        if ($attackerfighters > $targetfighters)
        {
            $txt['bnt_cmb_enemylostallfighters'] = str_replace("[cmb_targetinfo_ship_name]", $targetinfo['ship_name'], $txt['bnt_cmb_enemylostallfighters']);
            echo '--> ', $txt['bnt_cmb_enemylostallfighters'], '<br>';
            $temptargfighters = 0;
        }
        else
        {
            $txt['bnt_cmb_helostsomefighters'] = str_replace("[cmb_targetinfo_ship_name]", $targetinfo['ship_name'], $txt['bnt_cmb_helostsomefighters']);
            $txt['bnt_cmb_helostsomefighters'] = str_replace("[cmb_attackerfighters]", $attackerfighters, $txt['bnt_cmb_helostsomefighters']);
            echo $txt['bnt_cmb_helostsomefighters'], '<br>';
            $temptargfighters = $targetfighters - $attackerfighters;
        }
        if ($targetfighters > $attackerfighters)
        {
            echo '<-- ', $txt['bnt_cmb_youlostallfighters'], '<br>';
            $tempplayfighters = 0;
        }
        else
        {
            $txt['bnt_cmb_youalsolostsomefighters'] = str_replace("[cmb_targetfighters]", $targetfighters, $txt['bnt_cmb_youalsolostsomefighters']);
            echo '<-- ', $txt['bnt_cmb_youalsolostsomefighters'], '<br>';
            $tempplayfighters = $attackerfighters - $targetfighters;
        }
        $attackerfighters = $tempplayfighters;
        $targetfighters = $temptargfighters;
    }
    elseif ($attackerfighters > 0 && $targetfighters < 1)
    {
        $txt['bnt_cmb_hehasnofightersleftattack'] = str_replace("[cmb_targetinfo_ship_name]", $targetinfo['ship_name'], $txt['bnt_cmb_hehasnofightersleftattack']);
        echo $txt['bnt_cmb_hehasnofightersleftattack'], '<br>';
    }
    else
    {
        $txt['bnt_cmb_younofightersattackleft'] = str_replace("[cmb_targetinfo_ship_name]", $targetinfo['ship_name'], $txt['bnt_cmb_younofightersattackleft']);
        echo $txt['bnt_cmb_younofightersattackleft'], '<br>';
    }
	
    if ($attackerfighters > 0)
    {
        if ($attackerfighters > $targetarmor)
        {
            $targetarmor = 0;
            $txt['bnt_cmb_youbreachedarmorwithfighters'] = str_replace("[cmb_targetinfo_ship_name]", $targetinfo['ship_name'], $txt['bnt_cmb_youbreachedarmorwithfighters']);
            echo '--> ', $txt['bnt_cmb_youbreachedarmorwithfighters'], '<br>';
        }
        else
        {
            $targetarmor = $targetarmor - $attackerfighters;
            $txt['bnt_cmb_youhitarmordmgfighters'] = str_replace("[cmb_targetinfo_ship_name]", $targetinfo['ship_name'], $txt['bnt_cmb_youhitarmordmgfighters']);
            $txt['bnt_cmb_youhitarmordmgfighters'] = str_replace("[cmb_attackerfighters]", $attackerfighters, $txt['bnt_cmb_youhitarmordmgfighters']);
            echo '<-- ', $txt['bnt_cmb_youhitarmordmgfighters'], '<br>';
        }
    }
    else
    {
        $txt['bnt_cmb_youhavenofighterstoarmor'] = str_replace("[cmb_targetinfo_ship_name]", $targetinfo['ship_name'], $txt['bnt_cmb_youhavenofighterstoarmor']);
        echo $txt['bnt_cmb_youhavenofighterstoarmor'] ,'<br>';
    }
	
    if ($targetfighters > 0)
    {
        if ($targetfighters > $attackerarmor)
        {
            $attackerarmor = 0;
            $txt['bnt_cmb_hasbreachedarmorfighters'] = str_replace("[cmb_targetinfo_ship_name]", $targetinfo['ship_name'], $txt['bnt_cmb_hasbreachedarmorfighters']);
            echo '<-- ', $txt['bnt_cmb_hasbreachedarmorfighters'], '<br>';
        }
        else
        {
            $attackerarmor = $attackerarmor - $targetfighters;
            $txt['bnt_cmb_yourarmorishitfordmgby'] = str_replace("[cmb_targetfighters]", $targetfighters, $txt['bnt_cmb_yourarmorishitfordmgby']);
            $txt['bnt_cmb_yourarmorishitfordmgby'] = str_replace("[cmb_targetinfo_ship_name]", $targetinfo['ship_name'], $txt['bnt_cmb_yourarmorishitfordmgby']);
            echo '--> ', $txt['bnt_cmb_yourarmorishitfordmgby'], '<br>';
        }
    }
    else
    {
        $txt['bnt_cmb_nofightersleftheforyourarmor'] = str_replace("[cmb_targetinfo_ship_name]", $targetinfo['ship_name'], $txt['bnt_cmb_nofightersleftheforyourarmor']);
        echo $txt['bnt_cmb_nofightersleftheforyourarmor'], '<br>';
    }
	
    if ($targetarmor < 1)
    {
        $txt['bnt_cmb_hehasbeendestroyed'] = str_replace("[cmb_targetinfo_ship_name]", $targetinfo['ship_name'], $txt['bnt_cmb_hehasbeendestroyed']);
        echo '<br>', $txt['bnt_cmb_hehasbeendestroyed'], '<br>';
		
        if ($attackerarmor > 0)
        {
            $rating_change = round($targetinfo['rating'] * $rating_combat_factor);
            $free_ore = round($targetinfo['ship_ore'] / 2);
            $free_organics = round($targetinfo['ship_organics'] / 2);
            $free_goods = round($targetinfo['ship_goods'] / 2);
            $free_holds = NUM_HOLDS($playerinfo['hull']) - $playerinfo['ship_ore'] - $playerinfo['ship_organics'] - $playerinfo['ship_goods'] - $playerinfo['ship_colonists'];
            
			if ($free_holds > $free_goods)
            {
                $salv_goods = $free_goods;
                $free_holds = $free_holds - $free_goods;
            }
            elseif( $free_holds > 0)
            {
                $salv_goods = $free_holds;
                $free_holds = 0;
            }
            else
            {
                $salv_goods = 0;
            }
			
            if ($free_holds > $free_ore)
            {
                $salv_ore = $free_ore;
                $free_holds = $free_holds - $free_ore;
            }
            elseif ($free_holds > 0)
            {
                $salv_ore = $free_holds;
                $free_holds = 0;
            }
            else
            {
                $salv_ore = 0;
            }
			
            if ($free_holds > $free_organics)
            {
                $salv_organics = $free_organics;
                $free_holds = $free_holds - $free_organics;
            }
            elseif ($free_holds > 0)
            {
                $salv_organics = $free_holds;
                $free_holds = 0;
            }
            else
            {
                $salv_organics = 0;
            }
			
            $ship_value = $upgrade_cost*(round(mypw($upgrade_factor, $targetinfo['hull'])) + round(mypw($upgrade_factor, $targetinfo['engines'])) + round(mypw($upgrade_factor, $targetinfo['power'])) + round(mypw($upgrade_factor, $targetinfo['computer'])) + round(mypw($upgrade_factor, $targetinfo['sensors'])) + round(mypw($upgrade_factor, $targetinfo['beams'])) + round(mypw($upgrade_factor, $targetinfo['torp_launchers'])) + round(mypw($upgrade_factor, $targetinfo['shields'])) + round(mypw($upgrade_factor, $targetinfo['armor'])) + round(mypw($upgrade_factor, $targetinfo['cloak'])));
            $ship_salvage_rate = rand(10,20);
            $ship_salvage = $ship_value * $ship_salvage_rate / 100;
            
			$txt['bnt_cmb_yousalvaged'] = str_replace("[cmb_salv_ore]", $salv_ore, $txt['bnt_cmb_yousalvaged']);
            $txt['bnt_cmb_yousalvaged'] = str_replace("[cmb_salv_organics]", $salv_organics, $txt['bnt_cmb_yousalvaged']);
            $txt['bnt_cmb_yousalvaged'] = str_replace("[cmb_salv_goods]", $salv_goods, $txt['bnt_cmb_yousalvaged']);
            $txt['bnt_cmb_yousalvaged'] = str_replace("[cmb_salvage_rate]", $ship_salvage_rate, $txt['bnt_cmb_yousalvaged']);
            $txt['bnt_cmb_yousalvaged'] = str_replace("[cmb_salvage]", $ship_salvage, $txt['bnt_cmb_yousalvaged']);
            $txt['bnt_cmb_yousalvaged'] = str_replace("[cmb_number_rating_change]", NUMBER(abs($rating_change)), $txt['bnt_cmb_yousalvaged']);
            echo $txt['bnt_cmb_yousalvaged'];
			
			$update = $smcFunc['db_query']('', '
				UPDATE {raw:db_ships}
				SET ship_ore = ship_ore + {int:salv_ore}, 
					ship_organics = ship_organics + {int:salv_organics}, 
					ship_goods = ship_goods + {int:salv_goods}, 
					credits = credits + {float:ship_salvage}
				WHERE ship_id = {int:ship_id}',
				array(
					'db_ships' => $dbtables['ships'],
					'ship_id' => $playerinfo['ship_id'],
					'salv_ore' => $salv_ore,
					'salv_organics' => $salv_organics,
					'salv_goods' => $salv_goods,
					'ship_salvage' => $ship_salvage
				)
			);
        }

        if ($targetinfo['dev_escapepod'] == "Y")
        {
            $rating = round($targetinfo['rating']/2);
            echo $txt['bnt_cmb_escapepodlaunched'], '<br><br>';
			
			$update = $smcFunc['db_query']('', '
				UPDATE {raw:db_ships}
				SET hull = 0,
					engines = 0,
					power = 0,
					sensors = 0,
					computer = 0,
					beams = 0,
					torp_launchers = 0,
					torps = 0,
					armor = 0,
					armor_pts = 100,
					cloak = 0,
					shields = 0,
					sector = 0,
					ship_organics = 0,
					ship_ore = 0,
					ship_goods = 0,
					ship_energy = {int:start_energy},
					ship_colonists = 0,
					ship_fighters = 100,
					dev_warpedit = 0,
					dev_genesis = 0,
					dev_beacon = 0,
					dev_emerwarp = 0,
					dev_escapepod = "N",
					dev_fuelscoop = "N",
					dev_minedeflector = 0,
					on_planet = "N",
					rating = {int:rating},
					cleared_defences = NULL,
					dev_lssd = "N"
				WHERE ship_id = {int:ship_id}',
				array(
					'db_ships' => $dbtables['ships'],
					'ship_id' => $targetinfo['ship_id'],
					'start_energy' => $start_energy,
					'rating' => $rating
				)
			);

            playerlog($targetinfo['ship_id'],LOG_ATTACK_LOSE, "$playerinfo[character_name]|Y");
            collect_bounty($playerinfo['ship_id'],$targetinfo['ship_id']);
        }
        else
        {
            playerlog($targetinfo['ship_id'], LOG_ATTACK_LOSE, "$playerinfo[character_name]|N");
            db_kill_player($targetinfo['ship_id']);
            collect_bounty($playerinfo['ship_id'],$targetinfo['ship_id']);
        }
    }
    else
    {
        $txt['bnt_cmb_youdidntdestroyhim'] = str_replace("[cmb_targetinfo_ship_name]", $targetinfo['ship_name'], $txt['bnt_cmb_youdidntdestroyhim']);
        echo $txt['bnt_cmb_youdidntdestroyhim'], '<br>';
        
		$target_rating_change = round($targetinfo['rating'] * .1);
        $target_armor_lost = $targetinfo['armor_pts'] - $targetarmor;
        $target_fighters_lost = $targetinfo['ship_fighters'] - $targetfighters;
        $target_energy = $targetinfo['ship_energy'];
		
        playerlog($targetinfo['ship_id'], LOG_ATTACKED_WIN, "$playerinfo[character_name] $armor_lost $fighters_lost");
		
		$update = $smcFunc['db_query']('', '
			UPDATE {raw:db_ships}
			SET ship_energy = {int:target_energy},
				ship_fighters = ship_fighters - {int:target_fighters_lost},
				armor_pts = armor_pts - {int:target_armor_lost}, 
				torps = torps - {int:targettorpnum}
			WHERE ship_id = {int:ship_id}',
			array(
				'db_ships' => $dbtables['ships'],
				'ship_id' => $targetinfo['ship_id'],
				'target_energy' => $target_energy,
				'target_fighters_lost' => $target_fighters_lost,
				'target_armor_lost' => $target_armor_lost,
				'targettorpnum' => $targettorpnum
			)
		);
    }
	
    echo '<br>_+_+_+_+_+_+_<br>
    ', $txt['bnt_cmb_shiptoshipcombatstats'], '<br>
    ', $txt['bnt_cmb_statattackerbeams'], ': ', $attackerbeams, '<br>
    ', $txt['bnt_cmb_statattackerfighters'], ': ', $attackerfighters, '<br>
    ', $txt['bnt_cmb_statattackershields'], ': ', $attackershields, '<br>
    ', $txt['bnt_cmb_statattackertorps'], ': ', $attackertorps, '<br>
    ', $txt['bnt_cmb_statattackerarmor'], ': ', $attackerarmor, '<br>
    ', $txt['bnt_cmb_statattackertorpdamage'], ': ', $attackertorpdamage, '<br>
    _+_+_+_+_+_+<br>';
	
	$unlock = $smcFunc['db_query']('', 'UNLOCK TABLES');
}
?>
